
package com.example.library;

import ohos.agp.components.AttrSet;
import ohos.agp.components.InputAttribute;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.app.Context;

public class BandCardEditText extends TextField implements Text.TextObserver {

    private static final String WHITE_SPACE = " ";
    private boolean shouldStopChange = false;
    private BankCardListener listener;

    public BandCardEditText(Context context) {
        this(context, null);
    }

    public BandCardEditText(Context context, AttrSet attrs) {
        this(context, attrs, "0");
    }

    public BandCardEditText(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        format(getText());
        shouldStopChange = false;
        setFocusable(1);
        setEnabled(true);
        setTouchFocusable(true);
        addTextObserver(this);
        setTextInputType(InputAttribute.PATTERN_NUMBER);
    }

    @Override
    public void onTextUpdated(String s, int start, int before, int count) {
        if (s.length() >= 24) {
            setText(s.substring(0, 23));
            format(s.substring(0, 23));
        } else {
            format(s);
        }
    }

    private void format(String editable) {
        if (shouldStopChange) {
            shouldStopChange = false;
            return;
        }

        shouldStopChange = true;

        String str = editable.trim().replaceAll(WHITE_SPACE, "");
        int len = str.length();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            builder.append(str.charAt(i));
            if (i == 3 || i == 7 || i == 11 || i == 15) {
                if (i != len - 1)
                    builder.append(WHITE_SPACE);
            }
        }
        setText(builder.toString());
        if (listener != null) {
            if (BankCardUtils.checkBankCard(getBankCardText())) {
                char[] ss = getBankCardText().toCharArray();
                listener.success(BankCardUtils.getNameOfBank(ss, 0));
            } else {
                listener.failure();
            }
        }
    }

    public String getBankCardText() {
        return getText().trim().replaceAll(WHITE_SPACE, "");
    }

    public void setBankCardListener(BankCardListener listener) {
        this.listener = listener;
    }
}
